//
//  XSImageFilterView.m
//  AudioVideo
//
//  Created by xueshan1 on 2019/10/10.
//  Copyright © 2019 xueshan1. All rights reserved.
//

#import "XSImageFilterView.h"
#import "XSImageFilterCollectionViewCell.h"
#import "XSImageFilterModel.h"

@interface XSImageFilterView ()<UICollectionViewDelegate,UICollectionViewDataSource,TNFilterColorViewDelegate>
{
    GPUImageBrightnessFilter *brightness; // 亮度
    GPUImageContrastFilter *contrast; // 对比度
    GPUImageSaturationFilter *saturation; // 饱和度
    GPUImageWhiteBalanceFilter *whiteBalance; // 色温
    GPUImageHighlightShadowFilter *hightlightShadow; // 高光
    GPUImageLevelsFilter *levels; // 色阶
    GPUImageHueFilter *hue; // HUE
    GPUImageRGBFilter *rgb; // 颜色
    GPUImageFilterPipeline *pipeLine; // 组合滤镜
}
//@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,assign)NSInteger selectedItemIndex;
@property (nonatomic, strong) NSArray<NSString *> *dataSource;
@property (nonatomic, strong) NSArray<NSString *> *iconNames;

@property (weak, nonatomic) IBOutlet UIView *sliderBgView;
@property (strong, nonatomic) IBOutlet XSSlider *slider;
@property (weak, nonatomic) IBOutlet UIButton *sliderSureBtn;
@property (weak, nonatomic) IBOutlet UILabel *sliderLabel;

@property(nonatomic,strong)GPUImageView *gpuImageView;
@property(nonatomic,strong)GPUImagePicture *gpuPicture;

@property (weak, nonatomic) IBOutlet UIView *filterColorBgView;
@property (nonatomic, strong)IBOutlet TNFilterColorView *filterColorView;

@end

@implementation XSImageFilterView

- (instancetype)initWithFrame:(CGRect)frame editedImage:(UIImage *)editedImage editedView:(UIImageView *)editedView;
{
    self = [super initWithFrame:frame];
    if (self) {
        self = [[[NSBundle mainBundle]loadNibNamed:@"XSImageFilterView" owner:self options:nil] firstObject];
        self.frame = frame;
        self.backgroundColor = [UIColor whiteColor];
        self.editedImage = editedImage;
        self.editedView = editedView;
        [self setupUI];
 
    }
    return self;
}

- (void)setupUI{
    self.dataSource = @[@"亮度", @"对比度", @"饱和度", @"色温", @"高光", @"阴影", @"颜色"];//, @"文字"
    self.iconNames = @[@"brightness", @"contrast", @"saturation", @"temp", @"hightlight", @"shadow", @"color"];//, @"text"
    self.selectedItemIndex = -1;
    
    self.flowLayout.itemSize = CGSizeMake(FilterViewItemWidth, FilterViewItemWidth);
    self.flowLayout.minimumLineSpacing = 0;
    self.flowLayout.minimumInteritemSpacing = 10;
    self.flowLayout.minimumLineSpacing = 0;
    self.flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerNib:[UINib nibWithNibName:@"XSImageFilterCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"XSImageFilterCollectionViewCell"];
    [self.collectionView reloadData];
    
    self.sliderBgView.frame = self.bounds;
    self.sliderBgView.hidden = YES;
    [self addSubview:self.sliderBgView];
    self.slider.value = 0;
    self.slider.minimumValue = -100.0;
    self.slider.maximumValue = 100.0;
 
    self.filterColorBgView.frame = self.bounds;
    self.filterColorView.delegate = self;
    self.filterColorBgView.hidden = YES;
    [self addSubview:self.filterColorBgView];

    [self setupFilter];

}

//组合滤镜
- (void)setupFilter{
    if (pipeLine) {
        return;
    }
    self.gpuPicture = [[GPUImagePicture alloc]initWithImage:self.editedImage smoothlyScaleOutput:YES];
    
    self.gpuImageView = [[GPUImageView alloc]initWithFrame:self.editedView.bounds];
    [self.editedView addSubview:self.gpuImageView];
    

    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        brightness  = [[GPUImageBrightnessFilter alloc] init];
        contrast    = [[GPUImageContrastFilter alloc] init];
        saturation  = [[GPUImageSaturationFilter alloc] init];
        whiteBalance= [[GPUImageWhiteBalanceFilter alloc] init];
        hightlightShadow = [[GPUImageHighlightShadowFilter alloc] init];
        rgb         = [[GPUImageRGBFilter alloc] init];
        
        pipeLine = [[GPUImageFilterPipeline alloc]initWithOrderedFilters:@[brightness, contrast, saturation, whiteBalance, hightlightShadow, rgb] input:self.gpuPicture output:self.gpuImageView];
        //    [sourcePicture addTarget:pipeline.output]; // 加上这段 编辑的时候闪烁
        
        __weak typeof(&*self.gpuPicture)weakSource = self.gpuPicture;
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSource processImage];
        });
    });
  
    
}

- (void)hideFilterView{
    self.gpuImageView.hidden = YES;
    [UIView animateWithDuration:0.2 animations:^{
        self.y = kHeight - self.height;
    }completion:^(BOOL finished) {
        self.hidden = YES;
    }];
}

- (void)showFilterView{
    self.gpuImageView.hidden = NO;
    self.hidden = NO;
    [UIView animateWithDuration:0.2 animations:^{
        self.y = kHeight - self.height;
    }];
}
//重置滤镜
- (void)resetFilter{
    brightness.brightness = 0.0;
    contrast.contrast = 1.0;
    saturation.saturation = 1.0;
    whiteBalance.temperature = 5000.0;
    hightlightShadow.highlights = 1.0;
    hightlightShadow.shadows = 0.0;
    rgb.red = 1.0;
    rgb.green = 1.0;
    rgb.blue = 1.0;
    [self.gpuPicture processImage];
    
    [self sliderSureAction:nil];
    [self filterColorSureAction:nil];
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataSource.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    XSImageFilterCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"XSImageFilterCollectionViewCell" forIndexPath:indexPath];
    
    
    cell.imageV.image = [UIImage imageNamed:self.iconNames[indexPath.item]];
    cell.titleLab.text = self.dataSource[indexPath.item];
    if (indexPath.item == self.selectedItemIndex) {
        cell.isSelected = YES;
    }else{
        cell.isSelected = NO;
    }
    
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
//    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    self.selectedItemIndex = indexPath.item;
    [self.collectionView reloadData];
    
    [self resetSliderValueAction];
}

- (IBAction)sliderSureAction:(id)sender {
    [UIView animateWithDuration:0.0 animations:^{
        self.sliderBgView.y = kHeight;
    } completion:^(BOOL finished) {
        self.sliderBgView.hidden = YES;
    }];
    
}
- (IBAction)filterColorSureAction:(id)sender {
    [UIView animateWithDuration:0.0 animations:^{
        self.filterColorBgView.y = kHeight;
    } completion:^(BOOL finished) {
        self.filterColorBgView.hidden = YES;
    }];
}

- (IBAction)sliderValueChanged:(XSSlider *)sender {
    NSLog(@"%f",sender.value);
  
    switch (self.selectedItemIndex) {
        case 0:
            // 亮度
            brightness.brightness = self.slider.value / 100.0;
            break;
        case 1:
            // 对比度
            contrast.contrast = self.slider.value / 100.0;
            break;
        case 2:
            // 饱和度
            saturation.saturation = self.slider.value / 100.0;
            break;
        case 3:
            // 色温
            whiteBalance.temperature = self.slider.value * 100.0;
            break;
        case 4:
            // 高光
            hightlightShadow.highlights = self.slider.value / 100.0;
            break;
        case 5:
            // 阴影
            hightlightShadow.shadows = self.slider.value / 100.0;
            break;
        default:
            break;
    }
    [self.gpuPicture processImage];
    
}

- (void)resetSliderValueAction {
    if (self.selectedItemIndex == 6) {
        self.filterColorBgView.hidden = NO;
        self.filterColorBgView.y = 0;

        
        return;
    }
    
    if (self.selectedItemIndex == 7) {
        
        return;
    }
    
    
    
    if (self.sliderBgView.isHidden) {
        self.sliderBgView.hidden = NO;
        self.sliderBgView.y = 0;
        self.sliderLabel.text = self.dataSource[self.selectedItemIndex];

    }
 
    //reset
    switch (self.selectedItemIndex) {
        case 0:
            // 亮度
            self.slider.value = brightness.brightness * 100.0;
            self.slider.minimumValue = -100.0;
            self.slider.maximumValue = 100.0;
            break;
        case 1:
            // 对比度
            self.slider.value = contrast.contrast * 100.0;
            self.slider.minimumValue = 0.0;
            self.slider.maximumValue = 400.0;
            break;
        case 2:
            // 饱和度
            self.slider.value = saturation.saturation * 100.0;
            self.slider.minimumValue = 0.0;
            self.slider.maximumValue = 200.0;
            break;
        case 3:
            // 色温
            self.slider.value = whiteBalance.temperature / 100.0;
            self.slider.minimumValue = 0.0;
            self.slider.maximumValue = 100.0;
            break;
        case 4:
            // 高光
            self.slider.value = hightlightShadow.highlights * 100.0;
            self.slider.minimumValue = 0.0;
            self.slider.maximumValue = 100.0;
            break;
        case 5:
            // 阴影
            self.slider.value = hightlightShadow.shadows * 100.0;
            self.slider.minimumValue = 0.0;
            self.slider.maximumValue = 100.0;
            break;
        default:
            break;
    }
    
}


- (IBAction)filterDoneAction:(id)sender {
    [pipeLine.filters.lastObject useNextFrameForImageCapture];
    [self.gpuPicture processImage];
    UIImage *image = [pipeLine.filters.lastObject imageFromCurrentFramebuffer];
    
    if (image) {
        if (self.finishFilterCallBack) {
            self.finishFilterCallBack(image);
        }
        
    }
    
    [self hideFilterView];
}

#pragma mark - delegate
- (void)filterColorView:(TNFilterColorView *)filterColorView didSelectedColor:(UIColor *)color {
    const CGFloat *components = CGColorGetComponents(color.CGColor);
    rgb.red = components[0];
    rgb.green = components[1];
    rgb.blue = components[2];
    [self.gpuPicture processImage];
}


@end
